package net.mfjassociates.financial.server.rest;


import java.io.IOException;
import java.net.URI;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import net.mfjassociates.financial.shared.domain.Document;



// Will map the resource to the URL documents
@Path("/documents")
public class DocumentsResource {

	// Allows to insert contextual objects into the class, 
	// e.g. ServletContext, Request, Response, UriInfo
	@Context
	UriInfo uriInfo;
	@Context
	Request request;


	// Return the list of documents to the user in the browser
	@GET
	@Produces(MediaType.TEXT_XML)
	public List<Document> getDocumentsBrowser() {
		List<Document> documents = Document.findAllDocuments();
		return documents; 
	}
	
	// Return the list of documents for applications
	@GET
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public List<Document> getDocuments() {
		List<Document> documents = Document.findAllDocuments();
		return documents; 
	}
	
	
	// retuns the number of documents
	// Use http://localhost:8080/de.vogella.jersey.document/rest/documents/count
	// to get the total number of records
	@GET
	@Path("count")
	@Produces(MediaType.TEXT_PLAIN)
	public String getCount() {
		long count = Document.countDocuments();
		return String.valueOf(count);
	}
	
	@POST
	@Produces(MediaType.TEXT_HTML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public void newDocument(
			@FormParam("id") String id,
			@FormParam("summary") String summary,
			@FormParam("description") String createdBy,
			@Context HttpServletResponse servletResponse
	) throws IOException {
		Document document = new Document();
		if (createdBy!=null){
			document.setCreatedBy(createdBy);
		}
		document.setId(Long.valueOf(id));
		document.persist();
		
		URI uri = uriInfo.getAbsolutePathBuilder().path(id).build();
		Response.created(uri).build();
		
		servletResponse.sendRedirect("../create_document.html");
	}
	
	
	// Defines that the next path parameter after documents is
	// treated as a parameter and passed to the documentResources
	// Allows to type http://localhost:8080/de.vogella.jersey.document/rest/documents/1
	// 1 will be treaded as parameter document and passed to documentResource
	@Path("{document}")
	public DocumentResource getDocument(
			@PathParam("document") String iden) {
		return new DocumentResource(uriInfo, request, iden);
	}
	
}
